package com.silverhaze.diamond.client.ui.dialogs;

import com.silverhaze.commons.ui.dialogs.DialogConnector;
import com.silverhaze.commons.utils.TimeConstants;
import com.silverhaze.commons.helpers.CommonUIHelper;
import com.silverhaze.diamond.common.entity.Service;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.client.utils.db.ServiceDataSource;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Date;

/**
 * SystemUser: Babanin
 * Date: 03.06.2009
 * Time: 14:42:17
 */
public class ClientTakeStuffDialog extends JDialog {
    private Service service;
    private DialogConnector<Date> connector;

    public ClientTakeStuffDialog(Service service, Frame owner, DialogConnector<Date> connector) {
        super(owner);

        this.service = service;
        this.connector = connector;

        initializeView();
    }

    private void initializeView() {
        setModal(true);
        setTitle("Возврат владельцу");
        getRootPane().setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        add(new JLabel("<html><b>С момента завершения сервиса прошло " + countDays(service.getServiceCompleteDate()) + " дней</b></html>"), BorderLayout.CENTER);
        add(
                CommonUIHelper.packInShiftedPanel(
                        CommonUIHelper.packInPanel(
                                CommonUIHelper.createHorizontalBox(
                                        new JButton(new AbstractAction("Отдать владельцу") {
                                            public void actionPerformed(ActionEvent e) {
                                                okPressed();
                                            }
                                        }), 2,
                                        new JButton(new AbstractAction("Отмена") {
                                            public void actionPerformed(ActionEvent e) {
                                                ClientTakeStuffDialog.this.dispose();
                                            }
                                        })
                                ),
                                BorderLayout.LINE_END
                        ),
                        5, 0, 0, 0),
                BorderLayout.SOUTH
        );

        pack();
        setLocationRelativeTo(null);
    }

    private int countDays(Date serviceCompleteDate) {
        return (int) ((System.currentTimeMillis() - serviceCompleteDate.getTime()) / TimeConstants.MLS_IN_DAY);
    }

    protected void okPressed() {
        final Date clientTaskStuffDate = new Date();
        service.setClientTaskStuffDate(clientTaskStuffDate);

        DAOLocator.getInstance().update(service);
        ServiceDataSource.getInstance().updateService(service);

        ClientTakeStuffDialog.this.dispose();
        connector.objectSelected(clientTaskStuffDate);
    }
}

